<template>
  <ContentWrap>
    <!-- 搜索工作栏：保持不变 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="航机员" prop="flightCrew">
        <el-input
          v-model="queryParams.flightCrew"
          placeholder="请输入航机员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进港航班" prop="inboundFlight">
        <el-input
          v-model="queryParams.inboundFlight"
          placeholder="请输入进港航班"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="预落时间" prop="preLandingTime">
        <el-input
          v-model="queryParams.preLandingTime"
          placeholder="请输入预落时间(HHmm)"
          clearable
          @input="handleTimeInput('preLandingTime', $event)"
          @blur="handleTimeBlur('preLandingTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="实落时间" prop="inboundTime">
        <el-input
          v-model="queryParams.inboundTime"
          placeholder="请输入实落时间(HHmm)"
          clearable
          @input="handleTimeInput('inboundTime', $event)"
          @blur="handleTimeBlur('inboundTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="起飞时间" prop="depTime">
        <el-input
          v-model="queryParams.depTime"
          placeholder="请输入起飞时间(HHmm)"
          clearable
          @input="handleTimeInput('depTime', $event)"
          @blur="handleTimeBlur('depTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机号" prop="machineNo">
        <el-input
          v-model="queryParams.machineNo"
          placeholder="请输入机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="queryParams.recordDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择记录日期"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openCreForm('create')"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 获取最新
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleSyncQuarter"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 同步季度计划
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:schedule-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- 列设置按钮 -->
        <el-button type="primary" plain @click="openColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：使用el-table + 分页组件 -->
  <ContentWrap>
    <div style="height: calc(62vh - 60px); overflow: auto">
      <el-table
        :data="list"
        :loading="loading"
        :row-class-name="tableRowClassName"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="60" fixed="left" :selectable="isRowSelectable" />

        <!-- 动态列渲染 -->
        <el-table-column
          v-for="column in tableColumns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
        >
          <template #default="scope">
            <render-cell :column="column" :row="scope.row" :value="scope.row[column.prop]" />
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-center; gap: 8px;">
              <el-button type="primary" link @click="openForm('update', scope.row.id)">
                查看详情
              </el-button>
              <el-button type="danger" link @click="deleteHandler(scope.row)"> 删除 </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件：新增 -->
    <div class="pagination-container" style="margin-top: 15px; text-align: right">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNo"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 50, 100]"
      />
    </div>
  </ContentWrap>

  <!-- 列设置弹窗：保持不变 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 25%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 数量编辑弹窗 -->
  <el-dialog
    title="编辑数量信息"
    v-model="quantityDialogVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form ref="quantityFormRef" :model="currentRow" label-width="120px">
      <el-form-item label="销售数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewSaleQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassSaleQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassSaleQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassSaleQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="配餐数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="quantityDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleQuantitySave">确定</el-button>
    </template>
  </el-dialog>

  <!-- 详情弹窗：新增 -->
  <el-dialog
    title="详情信息"
    v-model="detailDialogVisible"
    width="800px"
    :close-on-click-modal="false"
    :before-close="handleDetailClose"
  >
    <div class="detail-content">
      <div class="text-center py-20">
        <p class="text-gray-500">详情内容区域</p>
      </div>
    </div>
    <template #footer>
      <el-button @click="detailDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 其他弹窗组件：保持不变 -->
  <FlightLogImportForm ref="importFormRef" @success="getList" />
  <!-- <ProduceRecordForm ref="formRef" @success="getList" /> -->
  <upIndexForm ref="formRef" @success="getList" />
  <ScheduleRecordForm ref="formCreRef" @success="getList" />
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed, watch, h } from 'vue'
import type { TableColumnCtx } from 'element-plus'
import {
  ElInput,
  ElButton,
  ElTag,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElIcon,
  ElTooltip,
  ElDialog,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElCheckbox,
  ElSelect,
  ElOption,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElLoading
} from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Setting,
  DArrowRight,
  Timer,
  BatchOperation
} from '@element-plus/icons-vue'

// 保留原始业务导入
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import FlightLogImportForm from './FlightLogImportForm.vue'
import { ShiftRecordApi } from '@/api/pplan/shiftrecord'
// import ProduceRecordForm from '@/views/pplan/producerecord/ProduceRecordForm.vue'
import upIndexForm from './upIndexForm.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'
import DictTag from '@/components/DictTag/src/DictTag.vue'
import { DICT_TYPE } from '@/utils/dict'
import ScheduleRecordForm from '@/views/distm/schedule/ScheduleRecordForm.vue'

/** 基础配置：保持不变 */
defineOptions({ name: 'ScheduleRecord' })
const message = useMessage()
const { t } = useI18n()

// 状态管理：保持不变（queryParams已包含分页参数）
const loading = ref(true)
const list = ref<ScheduleRecordVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  flightNo: undefined,
  depTime: undefined,
  flightCrew: undefined,
  inboundFlight: undefined,
  machineNo: undefined,
  inboundTime: undefined,
  preLandingTime: undefined,
  recordDate: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

// 新增：选择列相关状态
const selectedRowKeys = ref<number[]>([]) // 选中的行ID集合
const batchDialogVisible = ref(false) // 批量操作弹窗
const batchForm = reactive({
  operationType: '', // 操作类型
  targetStatus: '' // 目标状态
})

// 数量编辑弹窗相关
const quantityDialogVisible = ref(false)
const currentRow = ref<Partial<ScheduleRecordVO>>({})
const quantityFormRef = ref()

// 详情弹窗相关：新增
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<ScheduleRecordVO | null>(null)

/** 生产状态：保持不变 */
const pstatusList = reactive([
  { value: 1, label: '餐食准备完成' },
  { value: 2, label: '机供品准备完成' },
  { value: 3, label: '任务分配完成' },
  { value: 4, label: '航机任务确认' },
  { value: 5, label: '装机' },
  { value: 6, label: '完成' },
  { value: 7, label: '发车确认' },
  { value: 8, label: '进入机坪' },
  { value: 9, label: '到达机位完成' },
  { value: 10, label: '开始保障' },
  { value: 11, label: '结束保障' },
  { value: 12, label: '起飞' },
  { value: 13, label: '取消装机' },
  { value: 14, label: '取消完成' }
])

/** 工具函数：保持不变 */
const getStatusLabel = (statusValue: number | string | undefined | null) => {
  if (!statusValue && statusValue !== 0) return '未开始'
  const numStatus = Number(statusValue)
  const matched = pstatusList.find((item) => item.value === numStatus)
  return matched ? matched.label : '未开始'
}

const formatTimeArray = (timeArr: any[]) => {
  if (!Array.isArray(timeArr) || timeArr.length !== 2) return ''
  const hour = String(timeArr[0]).padStart(2, '0')
  const minute = String(timeArr[1]).padStart(2, '0')
  return `${hour}:${minute}`
}

const normalizeTimeFormat = (timeValue: any): string => {
  if (!timeValue) return ''
  if (Array.isArray(timeValue) && timeValue.length === 2) {
    return formatTimeArray(timeValue)
  }
  if (typeof timeValue === 'string') {
    if (/^\d{2}:\d{2}$/.test(timeValue)) return timeValue
    if (/^\d{4}$/.test(timeValue)) {
      return `${timeValue.slice(0, 2)}:${timeValue.slice(2, 4)}`
    }
  }
  return ''
}

const formatTimeString = (timeString: string): string | null => {
  if (timeString.includes(':')) return timeString
  if (!/^\d{4}$/.test(timeString)) return null
  const hours = parseInt(timeString.slice(0, 2))
  const minutes = parseInt(timeString.slice(2, 4))
  if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) {
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
  }
  return null
}

const formatDisplayTime = (timeString: string | undefined): string | null => {
  if (!timeString) return null
  return formatTimeString(timeString)
}

const isTimeColumn = (prop: string): boolean => {
  return ['inboundTime', 'preLandingTime', 'depTime'].includes(prop)
}

const isNumberColumn = (prop: string): boolean => {
  return [
    'crewQty',
    'bussClassQty',
    'premEcoClassQty',
    'ecoClassQty',
    'crewSaleQty',
    'bussClassSaleQty',
    'premEcoClassSaleQty',
    'ecoClassSaleQty'
  ].includes(prop)
}

const getColumnNameByProp = (prop: string): string => {
  const column = tableColumns.find((col) => col.prop === prop)
  return column?.label || prop
}

/** 业务逻辑：保持不变（getList已使用分页参数） */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.pageTodayEdit(queryParams)
    list.value = data.list || []
    list.value.forEach((item) => {
      item.inboundTime = normalizeTimeFormat(item.inboundTime)
      item.preLandingTime = normalizeTimeFormat(item.preLandingTime)
      item.depTime = normalizeTimeFormat(item.depTime)
      item._original = JSON.parse(JSON.stringify(item))
      item.formattedOriginal = {
        inboundTime: item.inboundTime || '',
        preLandingTime: item.preLandingTime || '',
        depTime: item.depTime || '',
        machineNo: item.machineNo || '',
        airportStands: item.airportStands || '',
        inboundFlight: item.inboundFlight || '',
        remarks: item.remarks || '',
        bussClassQty: item.bussClassQty || '',
        crewSaleQty: item.crewSaleQty || '',
        bussClassSaleQty: item.bussClassSaleQty || '',
        premEcoClassSaleQty: item.premEcoClassSaleQty || '',
        ecoClassSaleQty: item.ecoClassSaleQty || '',
        crewQty: item.crewQty || '',
        premEcoClassQty: item.premEcoClassQty || '',
        ecoClassQty: item.ecoClassQty || '',
        specialRemarks: item.specialRemarks || ''
      }
    })
    total.value = data.total || 0 // 绑定总条数
    selectedRowKeys.value = []
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1 // 搜索时重置页码为第一页
  getList()
}

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  // 重置分页参数
  queryParams.pageNo = 1
  queryParams.pageSize = 10
  handleQuery()
}

// 新增：分页事件处理函数
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  queryParams.pageNo = 1 // 每页条数变化时重置页码
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getList()
}

// 其他业务逻辑：保持不变
const formRef = ref()
const openForm = (type: string, flightNo?: string) => {
  formRef.value.openFlightNo(type, flightNo)
}

const formCreRef = ref()
const openCreForm = (type: string, id?: number) => {
  formCreRef.value.open(type, id)
}

const formAddRef = ref()
const openAddForm = (flightNo?: string, recordDate?: string) => {
  if (formAddRef.value && flightNo) formAddRef.value.openAdd('create', flightNo, recordDate)
}

// 删除操作：修改为使用新API并添加二次确认
const deleteHandler = async (row: ScheduleRecordVO) => {
  try {
    await message.delConfirm() // 二次确认
    if (!row.id) {
      message.error('数据ID无效')
      return
    }
    await ScheduleRecordApi.deleteTodayEdit(row.id) // 使用新的删除API
    message.success(t('common.delSuccess'))
    await getList()
  } catch (err) {
    console.error('删除失败:', err)
    message.error(t('common.delFail'))
  }
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await ScheduleRecordApi.exportScheduleRecord(queryParams)
    download.excel(data, '配送管理-调度生产记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleSyncQuarter = async () => {
  try {
    await message.exportConfirm('同步季度计划会重置今日计划和生产计划，是否同步季度计划？')
    exportLoading.value = true
    await ScheduleRecordApi.syncQuarterPlan()
    message.success('同步季度计划成功')
    await getList()
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleFieldChange = async (row: ScheduleRecordVO) => {
  try {
    if (!row || !row.id) {
      message.error('数据无效')
      return
    }

    const hasChange = Object.keys(row).some((key) => {
      if (key === '_original' || key === 'formattedOriginal') return false
      const original = row.formattedOriginal[key] || ''
      const current = row[key] || ''
      if (isTimeColumn(key)) return original !== current
      if (isNumberColumn(key)) return String(original) !== String(current)
      return original !== current
    })

    if (!hasChange) return

    const updateData = {
      ...row,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      crewSaleQty: row.crewSaleQty ? Number(row.crewSaleQty) : undefined,
      bussClassSaleQty: row.bussClassSaleQty ? Number(row.bussClassSaleQty) : undefined,
      premEcoClassSaleQty: row.premEcoClassSaleQty ? Number(row.premEcoClassSaleQty) : undefined,
      ecoClassSaleQty: row.ecoClassSaleQty ? Number(row.ecoClassSaleQty) : undefined,
      crewQty: row.crewQty ? Number(row.crewQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined
    } as ScheduleRecordVO

    const res = await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(res !== 'success' ? res : t('common.updateSuccess'))

    row._original = JSON.parse(JSON.stringify(row))
    row.formattedOriginal = {
      inboundTime: row.inboundTime || '',
      preLandingTime: row.preLandingTime || '',
      depTime: row.depTime || '',
      machineNo: row.machineNo || '',
      airportStands: row.airportStands || '',
      inboundFlight: row.inboundFlight || '',
      remarks: row.remarks || '',
      bussClassQty: row.bussClassQty || '',
      crewSaleQty: row.crewSaleQty || '',
      bussClassSaleQty: row.bussClassSaleQty || '',
      premEcoClassSaleQty: row.premEcoClassSaleQty || '',
      ecoClassSaleQty: row.ecoClassSaleQty || '',
      crewQty: row.crewQty || '',
      premEcoClassQty: row.premEcoClassQty || '',
      ecoClassQty: row.ecoClassQty || '',
      specialRemarks: row.specialRemarks || ''
    }
  } catch (err) {
    console.error('更新失败:', err)
    message.error(t('common.updateFail'))
    await getList()
  }
}

const handleQuantitySave = async () => {
  try {
    if (!currentRow.value.id) {
      message.error('数据无效')
      return
    }
    const tempRow = JSON.parse(JSON.stringify(currentRow.value)) as ScheduleRecordVO
    await handleFieldChange(tempRow)
    quantityDialogVisible.value = false
    await getList()
  } catch (err) {
    console.error('数量更新失败:', err)
    message.error(t('common.updateFail'))
  }
}

const handleStatusChange = async (row: ScheduleRecordVO, newStatus: number) => {
  try {
    if (row.pstatus === newStatus) return
    await ScheduleRecordApi.updateScheduleRecord({ id: row.id, pstatus: newStatus })
    row.pstatus = newStatus
    message.success(t('common.updateSuccess'))
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('生产状态更新失败：', err)
  }
}

const importFormRef = ref()
const handleImportLog = () => importFormRef.value?.open()

const handleTimeInput = (field: string, value: string) => {
  queryParams[field] = value.replace(/[^0-9]/g, '')
}

const handleTimeBlur = (field: string) => {
  const value = queryParams[field]
  if (!value) return
  if (/^\d{2}:\d{2}$/.test(value)) return
  if (value.length !== 4 || !/^\d{4}$/.test(value)) {
    message.error('请输入4位数字的时间格式(HHmm)')
    queryParams[field] = ''
    return
  }
  const formatted = formatTimeString(value)
  queryParams[field] = formatted || ''
  if (!formatted) message.error('请输入有效的时间格式(HHmm)')
}

const handleColumnTimeBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && /^\d{2}:\d{2}$/.test(current)) {
    await handleFieldChange(row)
    return
  }

  if (current && (current.length !== 4 || !/^\d{4}$/.test(current))) {
    message.error(`请输入4位数字的${getColumnNameByProp(prop)}格式(HHmm)`)
    row[prop] = original
    return
  }

  if (current) {
    const formatted = formatTimeString(current)
    if (formatted) {
      if (formatted === original) {
        row[prop] = formatted
        return
      }
      row[prop] = formatted
      await handleFieldChange(row)
    } else {
      message.error('请输入有效的时间格式(HHmm)')
      row[prop] = original
    }
  } else {
    if (original !== '') await handleFieldChange(row)
  }
}

const handleNumberBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && (isNaN(parseInt(current)) || parseInt(current) < 0)) {
    message.error(`请输入有效的${getColumnNameByProp(prop)}`)
    row[prop] = original
    return
  }

  await handleFieldChange(row)
}

const handleTextBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return
  await handleFieldChange(row)
}

const handleColumnTimeInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleNumberInput = (row: any, prop: string, value: string) => {
  const numericValue = value.replace(/[^0-9]/g, '')
  row[prop] = numericValue.slice(0, 9)
}

const handleSelectionChange = (val: ScheduleRecordVO[]) => {
  selectedRowKeys.value = val.map((item) => item.id).filter((id) => id !== undefined) as number[]
}

const isRowSelectable = (row: ScheduleRecordVO) => {
  return row.pstatus !== 12
}

const handleBatchOperation = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请先选择要操作的记录')
    return
  }
  batchForm.operationType = ''
  batchForm.targetStatus = ''
  batchDialogVisible.value = true
}

const confirmBatchOperation = async () => {
  if (!batchForm.operationType) {
    message.error('请选择操作类型')
    return
  }

  try {
    loading.value = true
    switch (batchForm.operationType) {
      case 'updateStatus':
        if (!batchForm.targetStatus) {
          message.error('请选择目标状态')
          return
        }
        await ScheduleRecordApi.batchUpdateStatus({
          ids: selectedRowKeys.value,
          pstatus: batchForm.targetStatus
        })
        message.success('批量更新状态成功')
        break
      case 'export':
        const data = await ScheduleRecordApi.exportScheduleRecord({
          ...queryParams,
          ids: selectedRowKeys.value
        })
        download.excel(data, '配送管理-调度生产记录-批量导出.xls')
        message.success('批量导出成功')
        break
      default:
        message.error('不支持的操作类型')
        return
    }
    batchDialogVisible.value = false
    await getList()
  } catch (err) {
    console.error('批量操作失败:', err)
    message.error('批量操作失败')
  } finally {
    loading.value = false
  }
}

/** 列设置：保持不变 */
const tableColumns = [
  {
    prop: 'inboundFlight',
    label: '进港航班',
    width: 150,
    editable: true,
    editWidth: 120,
    type: '文本'
  },
  { prop: 'flightNo', label: '航班号', width: 120, type: '文本' },
  { prop: 'route', label: '航线', width: 180, type: '文本' },
  { prop: 'machineNo', label: '机号', width: 130, editable: true, editWidth: 100, type: '文本' },
  { prop: 'depTime', label: '起飞时间', width: 120, editable: true, editWidth: 90, type: '时间' },
  {
    prop: 'preLandingTime',
    label: '预落时间',
    width: 120,
    editable: true,
    editWidth: 90,
    type: '时间'
  },
  {
    prop: 'inboundTime',
    label: '实落时间',
    width: 120,
    editable: true,
    editWidth: 90,
    type: '时间'
  },
  { prop: 'recordDate', label: '日期', width: 120, type: '日期' },
  {
    prop: 'airportStands',
    label: '机位',
    width: 130,
    editable: true,
    editWidth: 100,
    type: '文本'
  },
  { prop: 'remarks', label: '备注', width: 200, editable: true, editWidth: 160, type: '文本' },
  {
    prop: 'quantity',
    label: '数量',
    width: 300,
    type: '复合'
  },
  {
    prop: 'specialRemarks',
    label: '特殊说明',
    width: 200,
    editable: true,
    editWidth: 160,
    type: '文本'
  },
  { prop: 'aircraftType', label: '机型', width: 120, type: '文本' },
  { prop: 'airlineComp', label: '所属公司', width: 120, type: '状态' },
  { prop: 'airlinePattern', label: '航班类型', width: 120, type: '状态' },
  { prop: 'company', label: '所属公司', width: 120, type: '文本' },
  { prop: 'createTime', label: '创建时间', width: 200, type: '时间' },
  { prop: 'pstatus', label: '生产状态', width: 120, type: '状态' }
]

const columnVisibility = ref<Record<string, boolean>>({})
const selectedColumns = ref<string[]>([])
const columnSettingVisible = ref(false)

const initColumnVisibility = () => {
  const visibility: Record<string, boolean> = {}
  const selected: string[] = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

const openColumnSetting = () => {
  columnSettingVisible.value = true
}

const saveColumnSettings = () => {
  const newVisibility: Record<string, boolean> = {}
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })
  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}

const openQuantityEdit = (row: ScheduleRecordVO) => {
  currentRow.value = JSON.parse(JSON.stringify(row))
  quantityDialogVisible.value = true
}

/** 详情弹窗相关方法：新增 */
const openDetail = async (row: ScheduleRecordVO) => {
  if (!row.id) {
    message.error('数据ID无效')
    return
  }
  
  detailDialogVisible.value = true
  detailLoading.value = true
  detailData.value = null
  
  try {
    // 调用详情API
    const data = await ScheduleRecordApi.getTodayEdit(row.id)
    detailData.value = data
  } catch (err) {
    console.error('获取详情失败:', err)
    message.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

const handleDetailClose = () => {
  detailData.value = null
}

/** 单元格渲染组件：保持不变 */
const RenderCell = (props: { column: any; row: ScheduleRecordVO; value: any }) => {
  const { column, row, value } = props
  const cellValue = value?.toString() || ''
  const isDisabled = row.pstatus === 12

  if (column.prop === 'quantity') {
    return (
      <div
        style="display: flex; flex-direction: column; gap: 2px; width: 100%; cursor: pointer;"
        onClick={() => openQuantityEdit(row)}
      >
        <div style="display: flex; font-weight: 500; font-size: 12px;">
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content="J" placement="top">
              <span>J</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content="S" placement="top">
              <span>S</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content="G" placement="top">
              <span>G</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content="Y" placement="top">
              <span>Y</span>
            </ElTooltip>
          </div>
        </div>

        <div style="display: flex; font-size: 12px;">
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.crewSaleQty || '-'} placement="top">
              <span>{row.crewSaleQty || '-'}</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.bussClassSaleQty || '-'} placement="top">
              <span>{row.bussClassSaleQty || '-'}</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.premEcoClassSaleQty || '-'} placement="top">
              <span>{row.premEcoClassSaleQty || '-'}</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.ecoClassSaleQty || '-'} placement="top">
              <span>{row.ecoClassSaleQty || '-'}</span>
            </ElTooltip>
          </div>
        </div>
        <div style="display: flex; font-size: 12px;">
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.crewQty || '-'} placement="top">
              <span>{row.crewQty || '-'}</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.bussClassQty || '-'} placement="top">
              <span>{row.bussClassQty || '-'}</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.premEcoClassQty || '-'} placement="top">
              <span>{row.premEcoClassQty || '-'}</span>
            </ElTooltip>
          </div>
          /
          <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
            <ElTooltip content={row.ecoClassQty || '-'} placement="top">
              <span>{row.ecoClassQty || '-'}</span>
            </ElTooltip>
          </div>
        </div>
      </div>
    )
  }

  if (column.editable) {
    if (isTimeColumn(column.prop)) {
      return (
        <ElInput
          modelValue={cellValue}
          onUpdate:modelValue={(val) => {
            row[column.prop] = val
          }}
          placeholder={`请输入${column.label}(HHmm)`}
          clearable
          class={`!w-${column.editWidth || 100}px`}
          onInput={(e) => handleColumnTimeInput(row, column.prop, e.target.value)}
          onBlur={() => handleColumnTimeBlur(row, column.prop)}
          show-word-limit
          disabled={isDisabled}
        />
      )
    }

    if (isNumberColumn(column.prop)) {
      return (
        <ElInput
          modelValue={cellValue}
          onUpdate:modelValue={(val) => {
            row[column.prop] = val
          }}
          placeholder={`请输入${column.label}`}
          clearable
          class={`!w-${column.editWidth || 100}px`}
          onInput={(e) => handleNumberInput(row, column.prop, e.target.value)}
          onBlur={() => handleNumberBlur(row, column.prop)}
          show-word-limit
          type="number"
          min="0"
          disabled={isDisabled}
        />
      )
    }

    return (
      <ElInput
        modelValue={cellValue}
        onUpdate:modelValue={(val) => {
          row[column.prop] = val
        }}
        placeholder={`请输入${column.label}`}
        clearable
        class={`!w-${column.editWidth || 100}px`}
        onBlur={() => handleTextBlur(row, column.prop)}
        show-word-limit
        disabled={isDisabled}
      />
    )
  }

  if (column.prop === 'pstatus') {
    return (
      <ElTag type="primary" class="flex items-center justify-center">
        {getStatusLabel(cellValue)}
      </ElTag>
    )
  }

  if (column.prop === 'airlineComp') {
    return h(DictTag, {
      type: DICT_TYPE.PPLAN_AIRLINE_ID,
      value: row.airlineComp
    })
  }
  if (column.prop === 'airlinePattern') {
    return h(DictTag, {
      type: DICT_TYPE.PPLAN_AIRLINE_TYPE,
      value: row.airlinePattern
    })
  }
  if (column.prop === 'recordDate') {
    const dateParts = cellValue.split(',')
    const [year, month, day] = dateParts.map(Number)
    const formattedMonth = String(month).padStart(2, '0')
    const formattedDay = String(day).padStart(2, '0')
    const formattedDate = `${year}-${formattedMonth}-${formattedDay}`
    return <span>{formattedDate}</span>
  }
if (column.prop === 'createTime') {
    // 确保 cellValue 是一个有效的数字（时间戳）
    const timestamp = typeof cellValue === 'number' ? cellValue : parseInt(cellValue, 10);
    
    // 检查时间戳是否有效
    if (isNaN(timestamp) || timestamp < 0) {
      return <span class="flex items-center justify-center">-</span>;
    }

    const date = new Date(timestamp);
    
    // 获取年、月、日
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth() 返回 0-11
    const day = date.getDate().toString().padStart(2, '0');
    
    // 获取时、分、秒
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    // 拼接成 "YYYY-MM-DD HH:mm:ss" 格式
    const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    return (
      <ElTooltip content={formatted} placement="top">
        <span class="flex items-center justify-center">
          <ElIcon class="mr-2">
            <Timer />
          </ElIcon>
          {formatted}
        </span>
      </ElTooltip>
    );
  }
  if (isTimeColumn(column.prop)) {
    const formatted = formatDisplayTime(cellValue) || '-'
    return (
      <ElTooltip content={formatted} placement="top">
        <span class="flex items-center justify-center">{formatted}</span>
      </ElTooltip>
    )
  }

  if (column.prop === 'route') {
    const depLoc = row.depLoc || ''
    const arrLoc = row.arrLoc || ''
    const routeText = depLoc && arrLoc ? `${depLoc} - ${arrLoc}` : '-'
    return (
      <ElTooltip content={routeText} placement="top">
        <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center ">
          {routeText}
        </div>
      </ElTooltip>
    )
  }

  if (column.prop === 'remarks' || column.prop === 'specialRemarks') {
    return (
      <ElTooltip content={cellValue || '-'} placement="top">
        <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center justify-center">
          {cellValue || '-'}
        </div>
      </ElTooltip>
    )
  }

  return <span class="flex items-center justify-center">{cellValue || '-'}</span>
}

const renderCell = (props: any) => <RenderCell {...props} />

/** 辅助配置：保持不变 */
const tableRowClassName = ({ row }: { row: ScheduleRecordVO }) => {
  return row?.markStatus === 1 ? 'row-first' : ''
}

/** 初始化：保持不变 */
onMounted(() => {
  initColumnVisibility()
  getList()
})

watch(selectedColumns, () => {}, { deep: true })

watch(
  list,
  () => {
    selectedRowKeys.value = []
  },
  { deep: true }
)
</script>

<style scoped>
/* 保留原始样式 */
:deep(.el-table__row.row-first) {
  background-color: #f26a6e !important;
}

.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}
:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}

:deep(.el-table__cell) {
  padding: 4px 8px !important;
  border-bottom: 1px solid #f0f0f0;
}
:deep(.el-table__header) {
  background-color: #f8fafc !important;
  border-bottom: 1px solid #e6e6e6;
}
:deep(.el-table__header-wrapper th) {
  font-weight: 500;
  color: #333;
  padding: 8px 8px !important;
}

:deep(.el-input__inner) {
  width: 100% !important;
  min-height: 28px !important;
}
:deep(.el-input) {
  margin: 0 !important;
}

.overflow-hidden {
  overflow: hidden;
}
.whitespace-nowrap {
  white-space: nowrap;
}
.text-ellipsis {
  text-overflow: ellipsis;
}

:deep(.el-tooltip:hover .text-ellipsis) {
  color: #409eff !important;
  cursor: help;
}

.batch-operation-content {
  padding: 10px 0;
}
.batch-operation-content p {
  margin-bottom: 15px;
  color: #666;
}
.text-primary {
  color: #409eff;
  font-weight: 500;
}

/* 分页组件样式：新增 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

:deep(.el-pagination__sizes) {
  margin-right: 10px;
}

:deep(.el-pagination__total) {
  color: #666;
}

/* 详情弹窗样式：新增 */
.detail-content {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.text-gray-500 {
  color: #999;
}

.py-20 {
  padding-top: 20px;
  padding-bottom: 20px;
}
</style>